import cv2
import numpy as np
def get_target_hole_position(image_bytes) -> int | None:
    """
    获取目标滑块位置
    """
    try:
        nppr = np.frombuffer(image_bytes,np.uint8)
        image_np= cv2.imdecode(nppr,cv2.IMREAD_COLOR)
        if image_np is None:
            print("你传入的图片数据为空")
            return None
    except Exception as e :
        print(f"传入的数据格式有问题，请确保传入的是图片字节流：{e}")
        return None 
    gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, 100, 200)
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    potential_holes_x = []
    for contour in contours:
        area = cv2.contourArea(contour)
        # print(f"面积:{area}")
        if 10000 < area < 20000:
            M = cv2.moments(contour)
            if M["m00"] != 0:
                cx = int(M["m10"] / M["m00"])
                potential_holes_x.append(cx)

    return max(potential_holes_x) if potential_holes_x else None
